package com.aydx.remotevaluezookeeper.config;

import com.aydx.remotevaluezookeeper.properties.ZkValueZookeeperProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;
import org.apache.curator.retry.RetryUntilElapsed;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.io.IOException;

@Slf4j
@Configuration
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class ZookeeperConfiguration {
    @Autowired
    ZkValueZookeeperProperties zkValueZookeeperProperties;

    @Autowired
    private ApplicationContext appContext;


    @Bean
    public CuratorTemplate zkClient() throws IOException {

        RetryPolicy retryPolicy = new RetryNTimes(this.zkValueZookeeperProperties.getRetryConnectionTimes(), this.zkValueZookeeperProperties.getSleepMsBetweenRetries());
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(zkValueZookeeperProperties.getUrl())
                .sessionTimeoutMs(zkValueZookeeperProperties.getTimeout())  // 会话超时时间
                .connectionTimeoutMs(this.zkValueZookeeperProperties.getConnectionTimeout()) // 连接超时时间
                .retryPolicy(retryPolicy)
                .namespace(zkValueZookeeperProperties.getBasename()) // 包含隔离名称
                .build();
        client.start();
        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
//                if(newState==ConnectionState.LOST){
//                    log.error("!!!!!!!!!!!!!!!!!!!!!! zookeeper session expire,restart application !!!!!!!!!!!!!!");
//                    System.exit(-1);
//                }
            }
        });

        CuratorTemplate zookeeperTemplate=new CuratorTemplate(client);
        return zookeeperTemplate;
    }
}
